import 'package:app/common/index.dart';
import 'package:app/models/response.dart';
import 'package:app/widgets/message.dart';
import 'package:creato_ui/creato_ui.dart';
import 'package:flutter/material.dart';

class ResponseHandler {
  static void handleResponse(
      {BuildContext? context, ResponseData? responseData}) {
    if (context == null || responseData == null) {
      return;
    }
    // 1000 代表请求成功，不弹窗提示，由调用者处理
    if (responseData.code == 1000) {
      return;
    }

    if (responseData.msg == null) {
      return;
    }

    // 2001 代表用户登录状态失效，需要清除缓存信息并跳转到登录页面
    if (responseData.code == 2001) {
      UserHelper.loginOut(context);
      Message.showToast(msg: responseData.msg!);
      return;
    }

    Message.showToast(msg: responseData.msg!);
  }

  static void handleError({BuildContext? context, int? statusCode}) {
    if (context == null || statusCode == null) {
      return;
    }

    switch (statusCode) {
      case 401:
        Message.showToast(msg: "请先登录");
        break;
      case 403:
        Message.showToast(msg: "无权限访问");
        break;
      case 404:
        Message.showToast(msg: "资源不存在");
        break;
      case 405:
        Message.showToast(msg: "方法不被允许");
        break;
      case 500:
        Message.showToast(msg: "服务器内部错误");
        break;
      case 502:
        Message.showToast(msg: "网关错误");
        break;
      default:
        Message.showToast(msg: "未知错误");
        break;
    }
  }
}
